#!/usr/bin/perl
# 2013/09/30 making dot file to draw hiveplot

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;

if(@ARGV != 6 or $ARGV[0] eq '--help'){
	die "Usage : $0 -i [association file] -o [dot file] -t [title]\n";
}

my %opt;
getopts("i:o:t:", \%opt);
my $FILE_in = $opt{i};
my $FILE_out = $opt{o};
my $TITLE = $opt{t};
#MACS_peak_61    I:3709079-3712078       MACS_peak_163   II:2201281-2204280      1       1       1
#MACS_peak_61    I:3709079-3712078       MACS_peak_244   III:1140340-1143339     1       1       1
#MACS_peak_61    I:3709079-3712078       MACS_peak_75    I:3999423-4002422       1       1       1
#MACS_peak_61    I:3709079-3712078       MACS_peak_278   III:2157318-2160317     1       1       1
#MACS_peak_61    I:3709079-3712078       MACS_peak_195   II:3872881-3875880      1       1       1

my %section;
my %association;
my $fh_in = IO::File->new($FILE_in) or die "cannot open $FILE_in: $!";
while($_ = $fh_in->getline()){
	s/\r?\n//;
	my ($name1, $loc1, $name2, $loc2, $interaction, $pval, $qval) = split /\t/;

	if($qval ne 'NA' and $qval > 0.05){
		next;
	}

	if($name1 !~ m/^MACS/){
		next;
	}
	if($name2 !~ m/^MACS/){
		next;
	}



	my ($chr1, $se1) = split /:/, $loc1;
	my ($start1, $end1) = split /\-/, $se1;
	my ($chr2, $se2) = split /:/, $loc2;
	my ($start2, $end2) = split /\-/, $se2;


	if($chr1 ne 'I' and $chr1 ne 'II' and $chr1 ne 'III'){
		next;
	}
	if($chr2 ne 'I' and $chr2 ne 'II' and $chr2 ne 'III'){
		next;
	}

	my $distance = 6000000;
	my $type = 'inter';
	if($chr1 eq $chr2){
		$type = 'intra';
		$distance = abs($start1 - $start2);
	}

	$section{$name1} = sprintf("%s [chr=%s pos=%d]", $name1, $chr1, $start1);
	$section{$name2} = sprintf("%s [chr=%s pos=%d]", $name2, $chr2, $start2);

	if($qval ne 'NA' and $qval <= 0.05){
		my $key = "$name1:$name2";
		$association{$key} = sprintf("%s -- %s [type=%s distance=%d]", $name1, $name2, $type, $distance);
	}
}
$fh_in->close();


my $fh_out = IO::File->new($FILE_out, 'w') or die "cannot write $FILE_out: $!";
$fh_out->print("graph $TITLE {\n");
foreach my $key (keys %section){
	$fh_out->print("$section{$key}\n");
}
foreach my $key(keys %association){
	$fh_out->print("$association{$key}\n");
}
$fh_out->print("}\n");
$fh_out->close();
